package com.binguo.helper;

import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class BarcodeUtil {
//
//    public static void main(String[] args) {
//        generateFile4("123434123412341234");
//    }

    /**
     * 生成base64图片文件
     *
     * @param msg
     * @return
     */
    public static String generateFile(String msg) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            QrcodeUtil.createQrCode(outputStream,msg,650,"PNG");

            byte[] data = outputStream.toByteArray();

            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String s = encoder.encode(data);//返回Base64编码过的字节数组字符串


//            return "data:image/png;base64," + s;
            return s.replaceAll("\\n", "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }



    /**
     * 生成base64图片文件
     *
     * @param msg
     * @return
     */
    public static String generateFile3(String msg) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            generate(msg, outputStream);

            byte[] data = outputStream.toByteArray();

            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String s = encoder.encode(data);//返回Base64编码过的字节数组字符串


//            return "data:image/png;base64," + s;
            return s.replaceAll("\\n", "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
    /**
     * 生成base64图片文件
     *
     * @param msg
     * @return
     */
    public static void generateFile4(String msg) {
        try {
            FileOutputStream outputStream = new FileOutputStream("/Users/jay/IdeaProjects/binguo/wxapi/target/a.png");
            QrcodeUtil.createQrCode(outputStream,msg,680,"PNG");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 生成base64图片文件
     *
     * @param msg
     * @return
     */
    public static String generateFile7(String msg) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            QrcodeUtil.createQrCode(outputStream,msg,1100,"PNG");

            byte[] data = outputStream.toByteArray();

            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String s = encoder.encode(data);//返回Base64编码过的字节数组字符串

//            return "data:image/png;base64," + s;
            return s.replaceAll("\\n", "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 生成base64图片文件
     *
     * @param msg
     * @return
     */
    public static void generateFile2(String msg, String filepath) {
        try {
            generate(msg, new FileOutputStream(filepath));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 生成到流
     *
     * @param msg
     * @param ous
     */
    public static void generate(String msg, OutputStream ous) {
        if (StringUtils.isEmpty(msg) || ous == null) {
            return;
        }
        Code39Bean bean = new Code39Bean();

        // 精细度
        final int dpi = 200;
        // module宽度
        final double moduleWidth = UnitConv.in2mm(1.0f / dpi);

        // 配置对象
        bean.setModuleWidth(moduleWidth);
        bean.setWideFactor(3);
        bean.doQuietZone(false);

        String format = "image/png";
        try {

            // 输出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);

            // 生成条形码
            bean.generateBarcode(canvas, msg);

            // 结束绘制
            canvas.finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static final int MIN_INDEX = 15730;
    private static final int MAX_INDEX = Integer.MAX_VALUE - MIN_INDEX;

    private static AtomicInteger index = new AtomicInteger(MIN_INDEX);

    public static String createPayCode(String id) {
        if (id.length() < 5) {
            id = "12345";
        }
        //时间戳
        long now = System.currentTimeMillis();
        //自增序列号
        int i = index.getAndIncrement();

        if(i > MAX_INDEX)
            index.set(MIN_INDEX);

        //格式化订单号（时间戳+自增序号）
        StringBuilder sb = new StringBuilder();
        sb.append(now).append(i);
        sb.delete(0,6);

        String[] b = new String[3];

        b[0] = id.substring(0, 2);
        b[1] = id.substring(2, 4);
        b[2] = id.substring(4, 5);

        int t = 12;
        for (int k=0;k<3;k++) {
            int j = new Random().nextInt(t);

            sb.insert(j, b[k]);

            t += 2;
        }

        String result = "9" + sb.toString();

        return result;
    }

}
